<template>
  <div v-if="nav.length>0&&muluVisible&&display" class="mulu">
    <div style="width: 100%;line-height: 20px;padding:15px 25px;color: #333;font-size: 20px">目录</div>
    <ul id="mulubox" ref="ul">
      <li v-for="item in nav" :key="item.anchor" :class="item.tag === 'H2'?'h2padding':''" :title="item.title" @click="toAnchorView(item.anchor)">{{ item.title }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'Mulu',
  props: {
    nav: {
      type: Array,
      default: null
    },
    display: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      muluVisible: false
    }
  },
  watch: {
    '$route.path': function(newVal, oldValue) {
      console.log('$route.name', newVal)
      if (newVal && newVal.indexOf('info') >= 0) {
        this.muluVisible = true
      }
    },
    '$route.params.id': function(newVal, oldVal) {
    }
  },
  created() {
    if (this.$route.path.indexOf('info') >= 0) {
      this.muluVisible = true
    }
  },
  methods: {
    getNavTitle() {
      this.nav = []
      const that = this
      window.setTimeout(function() {
        var h1 = document.querySelectorAll('h1')
        h1.forEach(e => {
          const tempObj = {
            anchor: '',
            title: '',
            tag: ''
          }
          tempObj.anchor = `${e.id}`
          tempObj.title = `${e.innerText}`
          tempObj.tag = `${e.tagName}`
          that.nav.push(tempObj)
          var next = e.nextElementSibling
          // eslint-disable-next-line no-constant-condition
          while (next !== null && next.tagName !== 'H1') {
            // 如果为二级标题
            if (next.tagName === 'H2') {
              that.nav.push({
                anchor: next.id,
                title: next.innerText,
                tag: next.tagName
              })
            }
            next = next.nextElementSibling
          }
        })
      }, 100)
    },
    // 去目录所在的地方
    toAnchorView(anchor) {
      document.getElementById(anchor).scrollIntoView()
    }
  }
}
</script>

<style scoped lang="less">
  .h2padding{
    padding-left: 25px !important;
  }
  .mulu{
    position: absolute;
    right: 0;
    width: 220px;
    max-height: 450px;
    overflow-y: auto;
    box-sizing: border-box;
    background-color: #fff;
    ul{
      padding: 0;
      li{
        margin-left: 10px;
        padding: 10px 0;
        list-style: none;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow-x: hidden;
        border-bottom: 1px solid rgb(83, 150, 228);
        &:hover{
          background-color: #99eaff;
          color: blue;
          cursor: pointer;
        }
      }
    }
  }
</style>
